﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Ledict.ConditionExtract.DAL;
using System.Data;
using Ledict.ConditionExtract.Model;
using Ledict.ConditionExtract.Common;
using System.Xml;
using System.Collections;
using System.IO;


namespace Ledict.ConditionExtract.BLL
{

    public class AnalysisXMLBLL
    {

        NewIDBLL newid = new NewIDBLL();
        CaseCauseDAL casecausedal = new CaseCauseDAL();
        SYS_InfoElementsDAL infoElementsDAL = new SYS_InfoElementsDAL();
        ArgumentTypeXmlDAL argumentTypeXmlDAL = new ArgumentTypeXmlDAL();
        Dictionary<string, string> AllChildDic = new Dictionary<string, string>();
        XmlLabel_SuitTypeRelDAL xmllabel_suittypereldal = new XmlLabel_SuitTypeRelDAL();
        RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        /// <summary>
        /// 解析并添加节点
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="HeadId"></param>
        /// <param name="HeadName"></param>
        public void AnalyAddXMLNode(XmlNodeList list, string HeadId, string HeadName, string username)
        {
            if (!String.IsNullOrEmpty(HeadId))
            {
                // XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                //XmlDocument document = new XmlDocument();
                //document.LoadXml(XMLText);
                //XmlNodeList list = document.GetElementsByTagName(HeadName);
                DataTable AllChildTd = new DataTable();
                string CNodeid = "";
                AllChildDic.Clear();
                if (list.Count > 0)
                {
                    #region 存储检验待删的节点及其下级
                    foreach (XmlNode CNode in list[0].ChildNodes)
                    {
                        //根据名字获取cc_ID
                        CNodeid = casecausedal.Exists(CNode.Name, HeadId);
                        if (!string.IsNullOrEmpty(CNodeid))
                        {
                            //根据CC_id获取节点子集
                            AllChildTd = casecausedal.GetAllChild(CNodeid);
                            for (int i = 0; i < AllChildTd.Rows.Count; i++)
                            {
                                AllChildDic.Add(AllChildTd.Rows[i]["CC_ID"].ToString(), AllChildTd.Rows[i]["CC_Name"].ToString());
                            }
                        }
                    }
                    #endregion
                    #region 添加节点(主要功能)
                    foreach (XmlNode node in list)
                    {
                        xmlProcess(node, HeadId, @"/" + node.Name, HeadId, username);
                    }
                    casecausedal.CaseCauseUpdateAllPid(HeadId);
                    #endregion
                    #region 标记待删的节点
                    if (AllChildDic.Count > 0)
                    {
                        foreach (var item in AllChildDic)
                        {
                            casecausedal.UpdateName(item.Key, item.Value);
                        }
                    }
                    #endregion
                }

            }
            else
            {

            }
        }

        /// <summary>
        /// 解析并添加节点
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="HeadId"></param>
        /// <param name="HeadName"></param>
        public void AnalyAddXMLNode1(XmlNodeList list, string HeadId, string HeadName, string username, string es_ID)
        {
            if (!String.IsNullOrEmpty(HeadId))
            {
                // XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                //XmlDocument document = new XmlDocument();
                //document.LoadXml(XMLText);
                //XmlNodeList list = document.GetElementsByTagName(HeadName);
                DataTable AllChildTd = new DataTable();
                string CNodeid = "";
                AllChildDic.Clear();
                if (list.Count > 0)
                {
                    //首先删除节点
                    infoElementsDAL.DeleteSYS_InfoElements1(HeadId, username);
                    #region 存储检验待删的节点及其下级
                    //foreach (XmlNode CNode in list[0].ChildNodes)
                    //{
                    //    //根据名字获取cc_ID
                    //    CNodeid = casecausedal.Exists(CNode.Name, HeadId);
                    //    if (!string.IsNullOrEmpty(CNodeid))
                    //    {
                    //        //根据CC_id获取节点子集
                    //        AllChildTd = casecausedal.GetAllChild(CNodeid);
                    //        for (int i = 0; i < AllChildTd.Rows.Count; i++)
                    //        {
                    //            AllChildDic.Add(AllChildTd.Rows[i]["CC_ID"].ToString(), AllChildTd.Rows[i]["CC_Name"].ToString());
                    //        }
                    //    }
                    //}
                    #endregion
                    #region 添加节点(主要功能)
                    foreach (XmlNode node in list)
                    {
                        xmlProcess1(node, HeadId, @"/" + node.Name, HeadId, username, es_ID);
                    }
                    //待用
                    //casecausedal.CaseCauseUpdateAllPid(HeadId);
                    #endregion
                    #region 标记待删的节点
                    //if (AllChildDic.Count > 0)
                    //{
                    //    foreach (var item in AllChildDic)
                    //    {
                    //        casecausedal.UpdateName(item.Key, item.Value);
                    //    }
                    //}
                    #endregion
                }

            }
        }



        /// <summary>
        /// 解析并添加节点
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="HeadId"></param>
        /// <param name="HeadName"></param>
        public void AnalyAddXMLNodeNew(XmlNodeList list, string HeadId, string HeadName, string username)
        {
            if (!String.IsNullOrEmpty(HeadId) && list.Count > 0)
            {
                #region 添加节点(主要功能)
                foreach (XmlNode node in list)
                {
                    xmlProcess(node, HeadId, HeadName, HeadId, username);
                }
                casecausedal.CaseCauseUpdateAllPid(HeadId);
                #endregion
            }
        }


        /// <summary>
        /// 处理当前节点的下级
        /// </summary>
        /// <param name="PNode"></param>
        /// <param name="PNodeId"></param>
        private void xmlProcess1(XmlNode PNode, string PNodeId, string PXMLRoute, string HeadId, string username, string esID)
        {
            #region  属性
            //model.EIC_AllParentID = nowNode.EIC_AllParentID + "," + model.EIC_ID;
            //model.EIC_AllParentName = nowNode.EIC_AllParentName + "," + model.EIC_Name;
            //model.EIC_level = model.EIC_AllParentName.Split(',').Length;
            if (PNode.Attributes != null && PNode.Attributes.Count > 0)//"属性"节点
            {
                string AttributeId = infoElementsDAL.Exists("属性", PNodeId);
                if (String.IsNullOrEmpty(AttributeId))
                {
                    SYS_InfoElements par = infoElementsDAL.GetInfoElementsByEICid(PNodeId);
                    SYS_InfoElements sInfoModel = new SYS_InfoElements();
                    sInfoModel.EIC_ID = newid.JudgeDoc_CreateID("SYS_InfoElements");
                    sInfoModel.EIC_Name = "属性";
                    sInfoModel.EIC_ParentID = PNodeId;
                    sInfoModel.EIC_Type = "t3";
                    sInfoModel.EIC_XmlPath = PXMLRoute;
                    sInfoModel.ES_ID = esID;
                    sInfoModel.EIC_AllParentID = par.EIC_AllParentID + "," + sInfoModel.EIC_ID;
                    sInfoModel.EIC_AllParentName = par.EIC_AllParentName + "," + sInfoModel.EIC_Name;
                    sInfoModel.EIC_level = sInfoModel.EIC_AllParentName.Split(',').Length;
                    sInfoModel.EIC_SerialNumb = Convert.ToDecimal(infoElementsDAL.GetNodeChildSerialNumber(PNodeId));
                    infoElementsDAL.AddSYS_InfoElements(sInfoModel, username);
                    AttributeId = sInfoModel.EIC_ID;
                }

                for (int i = 0; i < PNode.Attributes.Count; i++)//下级属性
                {
                    string AttributesName = PNode.Attributes[i].LocalName;
                    if (!string.IsNullOrEmpty(AttributesName))
                    {
                        SYS_InfoElements par = infoElementsDAL.GetInfoElementsByEICid(AttributeId);
                        SYS_InfoElements NewModel = new SYS_InfoElements();
                        NewModel.EIC_ID = newid.JudgeDoc_CreateID("SYS_InfoElements");
                        NewModel.EIC_Name = AttributesName;
                        NewModel.EIC_ParentID = AttributeId;
                        NewModel.EIC_Type = "t3";
                        NewModel.ES_ID = esID;
                        NewModel.EIC_AllParentID = par.EIC_AllParentID + "," + NewModel.EIC_ID;
                        NewModel.EIC_AllParentName = par.EIC_AllParentName + "," + NewModel.EIC_Name;
                        NewModel.EIC_level = NewModel.EIC_AllParentName.Split(',').Length;
                        NewModel.EIC_XmlPath = PXMLRoute + @"/" + "@" + PNode.Attributes[i].LocalName;
                        NewModel.EIC_SerialNumb = Convert.ToDecimal(infoElementsDAL.GetNodeChildSerialNumber(NewModel.EIC_ParentID));
                        infoElementsDAL.AddSYS_InfoElements(NewModel, username);
                    }
                }
            }
            #endregion

            #region 下级节点
            foreach (XmlNode CNode in PNode.ChildNodes)//下级节点 
            {
                SYS_InfoElements par = infoElementsDAL.GetInfoElementsByEICid(PNodeId);

                #region 添加节点入库
                string CNodeid = string.Empty;
                SYS_InfoElements NewModel = new SYS_InfoElements();
                NewModel.EIC_ID = newid.JudgeDoc_CreateID("SYS_InfoElements");
                NewModel.EIC_Name = CNode.Name;
                NewModel.EIC_ParentID = PNodeId;
                NewModel.ES_ID = esID;
                NewModel.EIC_Type = "t2";
                NewModel.EIC_XmlPath = PXMLRoute + @"/" + CNode.Name;
                NewModel.EIC_AllParentID = par.EIC_AllParentID + "," + NewModel.EIC_ID;
                NewModel.EIC_AllParentName = par.EIC_AllParentName + "," + NewModel.EIC_Name;
                NewModel.EIC_level = NewModel.EIC_AllParentName.Split(',').Length;
                NewModel.EIC_SerialNumb = Convert.ToDecimal(infoElementsDAL.GetNodeChildSerialNumber(NewModel.EIC_ParentID));
                infoElementsDAL.AddSYS_InfoElements(NewModel, username);
                CNodeid = NewModel.EIC_ID;

                xmlProcess1(CNode, CNodeid, PXMLRoute + @"/" + CNode.Name, HeadId, username, esID);

                #endregion
            }
            #endregion
        }



        public string AnalyArgumentTypeXml(string XMLText)
        {

            List<string> list = new List<string>();
            StringBuilder Againlist = new StringBuilder();
            Againlist.Append("重复路径：");
            MatchCollection matchs = System.Text.RegularExpressions.Regex.Matches(XMLText, "xmlPath=\".*?\"");
            foreach (Match str in matchs)
            {
                if (!list.Contains(str.ToString()))
                    list.Add(str.ToString());
                else { Againlist.Append(str.ToString() + ","); }
            }
            return Againlist.ToString();
        }
        //public void AnalyArgumentTypeXml(string XMLText, string HeadId)
        //{
        //    XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("、", @"");
        //    XMLText = getregex.GetParseValue("EI1512151449150001", XMLText);
        //    XmlDocument document = new XmlDocument();
        //    document.LoadXml(XMLText);
        //    XmlNodeList list = document.GetElementsByTagName("elementConfig");
        //    XmlNodeList Childlist = list[0].ChildNodes;
        //    if (Childlist.Count > 0)
        //    {
        //        foreach (XmlNode node in Childlist)
        //        {
        //            ADDOneArgumentType(node, HeadId);
        //        }
        //    }
        //}

        private void ADDOneArgumentType(XmlNode PNode, string HeadId)
        {
            SYS_ArgumentTypeXml XmlModel = new SYS_ArgumentTypeXml();
            XmlModel.CauseID = HeadId;

            #region  属性

            if (PNode.Attributes.Count > 0)//"属性"节点
            {

                for (int i = 0; i < PNode.Attributes.Count; i++)//下级属性
                {
                    string AttributesName = PNode.Attributes[i].LocalName;
                    string AttributesValue = PNode.Attributes[i].Value;
                    if (AttributesName == "xmlPath")
                    {
                        XmlModel.XmlPath = AttributesValue;
                        break;
                    }
                }
            }
            if (XmlModel.XmlPath != "")
            {
                DataTable dt = casecausedal.GetSYS_CaseCauseByXmlPath(XmlModel.XmlPath);
                if (dt.Rows.Count > 0)
                {
                    XmlModel.ElementID = dt.Rows[0]["CC_ID"].ToString();
                    XmlModel.ElementName = dt.Rows[0]["CC_Name"].ToString();
                }
            }
            #endregion
            string Name = "";
            string Value = "";
            #region 下级节点
            foreach (XmlNode CNode in PNode.ChildNodes)//下级节点 
            {
                Name = CNode.Name;
                Value = CNode.InnerText;

                if (Name == "checkType")
                    XmlModel.Paramter_ISCheck = Value == "check" ? 1 : 0;

                if (Name == "sourceType")
                    XmlModel.SourctType = Value;

                if (Name == "matchKeywords")
                {
                    XmlModel.AT_MatchKeyWord = Value;
                    XmlModel.SourceContent = System.Text.RegularExpressions.Regex.Replace(XmlModel.AT_MatchKeyWord, "[,，].*?(?=(；|;|$))", "");
                }
            }
            #endregion
            if (!String.IsNullOrEmpty(XmlModel.ElementID) && XmlModel.SourctType == "paramter")
            {
                XmlModel.ATX_ID = argumentTypeXmlDAL.Exists(XmlModel);
                if (XmlModel.ATX_ID == "")//没有加
                {
                    XmlModel.ATX_ID = newid.JudgeDoc_CreateID("SYS_ArgumentType_Xml");
                    argumentTypeXmlDAL.Add(XmlModel);
                }
                else //没有改
                {
                    argumentTypeXmlDAL.Update(XmlModel);
                }
            }
        }

        /// <summary>
        /// 处理当前节点的下级
        /// </summary>
        /// <param name="PNode"></param>
        /// <param name="PNodeId"></param>
        private void xmlProcess(XmlNode PNode, string PNodeId, string PXMLRoute, string HeadId, string username)
        {
            #region  属性

            if (PNode.Attributes != null && PNode.Attributes.Count > 0)//"属性"节点
            {
                string AttributeId = casecausedal.Exists("属性", PNodeId);
                if (!String.IsNullOrEmpty(AttributeId))
                {
                    AllChildDic.Remove(AttributeId);
                }
                else
                {
                    SYS_CaseCause NewModel = new SYS_CaseCause();
                    NewModel.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                    NewModel.CC_Name = "属性";
                    NewModel.PIS_ShowName = NewModel.CC_Name;
                    NewModel.CC_ParentID = PNodeId;
                    NewModel.isLeafNode = 0;
                    NewModel.CC_NodeType = 12;
                    NewModel.XmlPath = PXMLRoute;
                    NewModel.CC_SerialNumb = casecausedal.ComputeSerialNumb(NewModel.CC_ParentID, "");
                    casecausedal.AddSYS_CaseCause(NewModel, username);
                    AttributeId = NewModel.CC_ID;
                }

                for (int i = 0; i < PNode.Attributes.Count; i++)//下级属性
                {
                    string AttributesName = PNode.Attributes[i].LocalName;
                    if (!AttributesName.Contains("表述"))
                    {
                        string NotCoreAttributeId = casecausedal.Exists(PNode.Attributes[i].LocalName, AttributeId);//是否存在
                        if (!String.IsNullOrEmpty(NotCoreAttributeId))//已存在
                        {
                            AllChildDic.Remove(NotCoreAttributeId);//去掉

                            SYS_CaseCause OldModel = casecausedal.GetCaseCauseByCcid(NotCoreAttributeId);
                            OldModel.CC_Name = AttributesName;
                            OldModel.PIS_ShowName = OldModel.CC_Name;
                            OldModel.CC_ParentID = AttributeId;
                            OldModel.CC_NodeType = 12;
                            OldModel.XmlPath = PXMLRoute + @"/" + "@" + PNode.Attributes[i].LocalName;
                            OldModel.CC_SerialNumb = casecausedal.ComputeSerialNumb(OldModel.CC_ParentID, "");
                            string[] strs = OldModel.XmlPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                            if (strs.Length > 1 && !string.IsNullOrEmpty(strs[1]))
                            {
                                DataTable caseCauseTable = casecausedal.GetCaseCauseTypeByNodeType();
                                if (caseCauseTable != null && caseCauseTable.Rows.Count > 0 && caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ").Length > 0)
                                {
                                    OldModel.CC_NodeSubType = Convert.ToInt32(caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ")[0]["CC_NodeType"].ToString());
                                }
                            }
                            casecausedal.UpdateSYS_CaseCause(OldModel, username);
                        }
                        else//新加
                        {

                            SYS_CaseCause NewModel = new SYS_CaseCause();
                            NewModel.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                            NewModel.CC_Name = AttributesName;
                            NewModel.PIS_ShowName = NewModel.CC_Name;
                            NewModel.CC_ParentID = AttributeId;
                            NewModel.isLeafNode = 0;
                            NewModel.CC_NodeType = 12;
                            NewModel.XmlPath = PXMLRoute + @"/" + "@" + PNode.Attributes[i].LocalName;
                            NewModel.CC_SerialNumb = casecausedal.ComputeSerialNumb(NewModel.CC_ParentID, "");
                            string[] strs = NewModel.XmlPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                            if (strs.Length > 1 && !string.IsNullOrEmpty(strs[1]))
                            {
                                DataTable caseCauseTable = casecausedal.GetCaseCauseTypeByNodeType();
                                if (caseCauseTable != null && caseCauseTable.Rows.Count > 0 && caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ").Length > 0)
                                {
                                    NewModel.CC_NodeSubType = Convert.ToInt32(caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ")[0]["CC_NodeType"].ToString());
                                }
                            }
                            casecausedal.AddSYS_CaseCause(NewModel, username);
                            NotCoreAttributeId = NewModel.CC_ID;
                        }
                    }
                }
            }
            #endregion

            #region 下级节点
            foreach (XmlNode CNode in PNode.ChildNodes)//下级节点 
            {
                #region 添加节点入库

                string CNodeid = casecausedal.Exists(CNode.Name, PNodeId);

                if (!String.IsNullOrEmpty(CNodeid))//已存在
                {
                    AllChildDic.Remove(CNodeid);//去掉

                    SYS_CaseCause OldModel = casecausedal.GetCaseCauseByCcid(CNodeid);
                    OldModel.CC_Name = CNode.Name;
                    OldModel.PIS_ShowName = OldModel.CC_Name;
                    OldModel.CC_ParentID = PNodeId;
                    OldModel.CC_NodeType = 11;
                    OldModel.XmlPath = PXMLRoute + @"/" + CNode.Name;
                    OldModel.CC_SerialNumb = casecausedal.ComputeSerialNumb(OldModel.CC_ParentID, "");
                    string[] strs= OldModel.XmlPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    if (strs.Length > 1 && !string.IsNullOrEmpty(strs[1]))
                    {
                        DataTable caseCauseTable = casecausedal.GetCaseCauseTypeByNodeType();
                        if (caseCauseTable != null && caseCauseTable.Rows.Count > 0&&caseCauseTable.Select(" CC_NodeTypeName='"+ strs[1] + "' ").Length>0)
                        {
                            OldModel.CC_NodeSubType =Convert.ToInt32(caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ")[0]["CC_NodeType"].ToString());
                        }
                    }                    
                        casecausedal.UpdateSYS_CaseCause(OldModel, username);
                }
                else//新加
                {

                    SYS_CaseCause NewModel = new SYS_CaseCause();
                    NewModel.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                    NewModel.CC_Name = CNode.Name;
                    NewModel.PIS_ShowName = NewModel.CC_Name;
                    NewModel.CC_ParentID = PNodeId;
                    NewModel.isLeafNode = 0;
                    NewModel.CC_NodeType = 11;
                    NewModel.XmlPath = PXMLRoute + @"/" + CNode.Name;
                    NewModel.CC_SerialNumb = casecausedal.ComputeSerialNumb(NewModel.CC_ParentID, "");
                    string[] strs = NewModel.XmlPath.Split(new char[] { '/' },StringSplitOptions.RemoveEmptyEntries);
                    if (strs.Length > 1 && !string.IsNullOrEmpty(strs[1]))
                    {
                        DataTable caseCauseTable = casecausedal.GetCaseCauseTypeByNodeType();
                        if (caseCauseTable != null && caseCauseTable.Rows.Count > 0 && caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ").Length > 0)
                        {
                            NewModel.CC_NodeSubType = Convert.ToInt32(caseCauseTable.Select(" CC_NodeTypeName='" + strs[1] + "' ")[0]["CC_NodeType"].ToString());
                        }
                    }
                    casecausedal.AddSYS_CaseCause(NewModel, username);
                    CNodeid = NewModel.CC_ID;
                }

                xmlProcess(CNode, CNodeid, PXMLRoute + @"/" + CNode.Name, HeadId, username);

                #endregion


            }
            #endregion
        }



        /// <summary>
        /// 更改XML属性
        /// </summary>
        /// <param name="XMLText"></param>
        /// <param name="XMLPath"></param>
        public string UpdateArgumentTypeXml(string XMLText, string XMLPath, string matchValue)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLText);
            XmlNodeList nodes = document.SelectNodes(string.Format("/elementConfig/element[@xmlPath='{0}']/matchKeywords", XMLPath));
            if (0 < nodes.Count)
            {
                nodes[0].InnerText = matchValue;
            }
            return FormatXml(document.InnerXml);
        }

        /// <summary>
        /// xml格式化
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private string FormatXml(string source)
        {
            StringBuilder sb = new StringBuilder();
            XmlTextWriter writer = null;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(source);

                writer = new XmlTextWriter(new StringWriter(sb));
                writer.Formatting = Formatting.Indented;

                doc.WriteTo(writer);
            }
            finally
            {
                if (writer != null) writer.Close();
            }

            return sb.ToString();
        }

    }
}
